package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.constant.ErrConstant;
import com.hdax.dm.dto.LoginDto;
import com.hdax.dm.entity.user.DmUser;
import com.hdax.dm.exception.DmException;
import com.hdax.dm.mappers.UserMapper;
import com.hdax.dm.mapstrucs.LoginDtoMapper;
import com.hdax.dm.service.SMSLoginService;
import com.hdax.dm.util.RandomCharacters;
import com.hdax.dm.utils.Token.TokenUtil;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SMSLoginSImpl extends ServiceImpl<UserMapper,DmUser> implements SMSLoginService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 调用redisTemplate里面的方法就能存储redis里
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private LoginDtoMapper smsLoginDtoMapper;

    @Override
    public CommonResponse<LoginDto> SMSLogin(String phone, String vcode) {
        //根据指定的key从redis读取数据
        String key="vcode:"+phone;
        String realCode=redisTemplate.opsForValue().get(key);
        if(realCode==null){
            throw new DmException(ErrConstant.ErrCodeConstant.NOT_EXISTS_VCODE,ErrConstant.ErrMsgConstant.NOT_EXISTS_MSG_VCODE);
        }
        //比较输入的是否正确
        if (!realCode.equals(vcode)){
            throw new DmException(ErrConstant.ErrCodeConstant.WRONG_CODE_VCODE,ErrConstant.ErrMsgConstant.WRONG_MSG_VCODE);
        }
        //登录成功！根据输入的手机号查询用户信息

        //根据输入的手机号查询用户信息
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("phone",phone);

        DmUser user= getOne(wrapper);
        LoginDto loginDto= smsLoginDtoMapper.toTarget(user);


        if(user==null){
            DmUser dmUser=new DmUser();
            dmUser.setPhone(phone);
            dmUser.setNickName(RandomCharacters.getRandomCharacters(6));
            baseMapper.insert(dmUser);
            user=getOne(wrapper);
        }else {
            loginDto.setGenTime(TokenUtil.createDate.getTime()+"");
            loginDto.setExtTime(TokenUtil.expireDate.getTime()+"");
            String token= TokenUtil.createToken(user.getId()+"",user.getNickName());
            loginDto.setToken(token);
            //把token存到redis中
            redisTemplate.opsForValue().set("token:"+user.getId(),token,30, TimeUnit.MINUTES);
        }

        return ResponseUtil.returnSuccess(loginDto);
    }

    @Override
    public CommonResponse<String> msg(String phone) {
        //防止用户频繁请求验证码
        String key="vcode:"+phone;
        if (redisTemplate.opsForValue().get(key)!=null){
            throw new DmException(ErrConstant.ErrCodeConstant.REPEAT_CODE_VCODE,ErrConstant.ErrMsgConstant.REPEAT_MSG_VCODE);
        }

        if (phone==null && phone.trim().length()!=11){
            throw new DmException(ErrConstant.ErrCodeConstant.ERR_CODE_PHONE_NUMBER,ErrConstant.ErrMsgConstant.ERR_MSG_PHONE_NUMBER);
        }
        //生成验证码
        Random random=new Random();
        Integer min=1000;
        Integer max=10000;
        Integer rand= random.nextInt(max);
        if (rand<min){
            rand= random.nextInt(max);
        }
        //将生成的验证码存储到redis里                                          timeout：超时时间,TimeUnit：时间单位
        redisTemplate.opsForValue().set("vcode:"+phone,rand+"",70L, TimeUnit.SECONDS);
        //发送验证码到消息队列
        Map<String,String> map=new HashMap<>();
        map.put("phone",phone);
        map.put("vcode",rand+"");
//        rabbitTemplate.convertAndSend("dmsms",map);
        return ResponseUtil.returnSuccess(rand+"");
    }


}

